package com.jeeplus.modules.work.queue.utils;

import javax.net.ssl.*;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * @author li yu
 * @date 2018/11/7 14:19
 */
public class HttpUtilsBDC {

	private static final Logger log = LoggerFactory.getLogger(HttpUtilsBDC.class);

	public static CloseableHttpClient httpclient;

	//public static final String KEY_STORE_TRUST_PATH = "D:\\soft\\cszs\\ca.cer"; // truststore的路径
	public static final String KEY_STORE_TRUST_PATH = "E:\\soft\\webfile\\bdc\\ca.cer"; // truststore的路径

	public static final String KEY_STORE_TYPE_JKS = "JKS"; // truststore的类型

	//public static final String KEY_STORE_CLIENT_PATH = "D:\\soft\\cszs\\高新服务.pfx";
	public static final String KEY_STORE_CLIENT_PATH = "E:\\soft\\webfile\\bdc\\高新服务.pfx";
	
	public static final String KEY_STORE_TYPE_P12 = "PKCS12";
	
	private static final String KEY_STORE_PASSWORD = "0113.Gx";
	
	// 获得池化得HttpClient
	static {
		SSLContext sslcontext = null;
		try {
			// 设置truststore
			KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
			InputStream ksIn = new FileInputStream(KEY_STORE_CLIENT_PATH);
			InputStream tsIn = new FileInputStream(new File(
					KEY_STORE_TRUST_PATH));
			KeyStore trustStore = getCertKeyStore(tsIn);
			try {
				keyStore.load(ksIn, KEY_STORE_PASSWORD.toCharArray());
			} finally {
				try {
					//ksIn.close();
					// tsIn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore,
					new TrustSelfSignedStrategy()).loadKeyMaterial(keyStore,
					KEY_STORE_PASSWORD.toCharArray()).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
				.<ConnectionSocketFactory> create().register("http",
						PlainConnectionSocketFactory.INSTANCE).register(
						"https",
						new SSLConnectionSocketFactory(sslcontext,
								new HostnameVerifier() {

									@Override
									public boolean verify(String hostname,
											SSLSession session) {
										return ("221.237.156.168"
												.equals(hostname));
									}
								})).build();
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
				socketFactoryRegistry);
		connManager.setMaxTotal(100);
		connManager.setDefaultMaxPerRoute(10);
		// 个性化设置某个url的连接
		connManager.setMaxPerRoute(
				new HttpRoute(new HttpHost("www.y.com", 80)), 20);
		httpclient = HttpClients.custom().setConnectionManager(connManager)
				.build();
	}

	private static KeyStore getCertKeyStore(InputStream tsIn)
			throws CertificateException, KeyStoreException,
			NoSuchAlgorithmException, IOException {
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		Certificate caCert = cf.generateCertificate(tsIn);
		KeyStore tk = KeyStore.getInstance(KeyStore.getDefaultType());
		tk.load(null);
		tk.setCertificateEntry("mca", caCert);
		return tk;
	}

	public static String SendPost(String str) {
		String result = "";
		HttpClientContext context = HttpClientContext.create();
		HttpPost request = new HttpPost("https://221.237.156.168:4432/BdcService/ClricBdcSercie/Invoke");
		// 设置请求的配置
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(
				60000).setConnectTimeout(50000).setConnectionRequestTimeout(50000)
				.build();
		request.setConfig(requestConfig);
		request.setEntity(new StringEntity(str, ContentType.APPLICATION_JSON));
		CloseableHttpResponse response = null;
		int statusCode;
		try {
			response = httpclient.execute(request, context);
			
			 statusCode = response.getStatusLine().getStatusCode();
	        if (statusCode != HttpStatus.SC_OK) {
	            request.abort();
	            return "Fail to connect . response code = " + statusCode + ". error.";
	        }
	        
	        context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();
			} catch (SocketTimeoutException e) {
				e.printStackTrace();
				return "{\"Content\":\"{\\\"MsgHeader\\\":{},\\\"MsgBody\\\":{\\\"RtnInfo\\\":{\\\"Result\\\":\\\"1111\\\",\\\"Desc\\\":\\\"请求超时，请检查网络！\\\"}}}\"}";
			} catch (IOException e) {
				e.printStackTrace();
				//System.out.println("服务器返回信息...:" + response + ".....");
				return "{\"Content\":\"{\\\"MsgHeader\\\":{},\\\"MsgBody\\\":{\\\"RtnInfo\\\":{\\\"Result\\\":\\\"1111\\\",\\\"Desc\\\":\\\"连接大系统时出现错误！\\\"}}}\"}";
			}
				// 首先处理非200请求
				if (statusCode != 200) {
					return "{\"Content\":\"{\\\"MsgHeader\\\":{},\\\"MsgBody\\\":{\\\"RtnInfo\\\":{\\\"Result\\\":"
							+ statusCode
							+ ",\\\"Desc\\\":"
							+ response.getEntity() + "}}}\"}";
				} else {
					// 处理200请求
					try {
						//System.out.println("..response.get...."+ EntityUtils.toString(response.getEntity()));
						result = EntityUtils.toString(response.getEntity());
					} catch (IOException e) {
						// return "解析返回结果错误，请联系管理员";
						e.printStackTrace();
						return "{\"Content\":\"{\\\"MsgHeader\\\":{},\\\"MsgBody\\\":{\\\"RtnInfo\\\":{\\\"Result\\\":\\\"1111\\\",\\\"Desc\\\":\\\"连接大系统成功，但是解析返回数据时出现错误！\\\"}}}\"}";
					}
				}
				//System.out.println("结果"+ result);
			return result;

	}

	public static void main(String[] args) {
//		System.out.println( SendPost("param:{" +
//				"\"MsgHeader\": {" +
//				"\"TrnCode\": \"BDC.1055.001.01\"," +
//				"\"RefId\": \"20220111S111164237\"," +
//				"\"ReqRefId\": \"\"," +
//				"\"Token\": \"\"," +
//				"\"Remark\": \"\"" +
//				"}," +
//				"\"MsgBody\": {" +
//				"\"LoginName\": \"admin\"," +
//				"\"PassWord\": \"123456\"" +
//				"}}"));
		String parameter="\"Content\":\"{\\\"MsgHeader\\\":{\\\"TrnCode\\\":\\\"BDC.9001.001.01\\\",\\\"RefId\\\":\\\"202201151500000001\\\",\\\"ReqRefId\\\":\\\"\\\",\\\"Token\\\":\\\"\\\",\\\"Remark\\\":\\\"\\\"},\\\"MsgBody\\\":{\\\"LoginName\\\":\\\"RYB_BDCJK\\\",\\\"PassWord\\\":\\\"jKb.Dc@7jD72\\\"}}\",\"OrgId\":\"43\",\"Sign\":\"9095F7D7E6FD17B0B2EAE7031976B1A9\",\"Timestamp\":\"1642247748\"}";
		String s = SendPost(parameter);
		System.out.println(s);
	}
	
}
